//快速入口组件
AI.Desktop = Event.$extend({
  defaultOptions:{
    tabId:'prodTab',
    contentId:'prodContent',
    title:'产品列表',
    openInstall:false,//是否打开安装部分
    openComment:false,//是否打开评论部分
    sql:"SELECT * FROM metasoftcfg WHERE 1 = 1",
    groupSql:"SELECT typecode,type FROM metasoftcfg GROUP BY typecode ORDER BY typecode",
    colSize:6,//4
    tabTpl:'<li><a href="#type-<%=TYPECODE%>" data-toggle="tab"><%=TYPE%></a></li>',
    contentTpl:'<div class="tab-pane fade" id="type-<%=TYPECODE%>"></div> ',
    cardTpl:'<div id="<%=card.id%>" name="<%=card.name%>" class="desk-card <%=card.colClass%>" ref="<%=card.url%>">'
      +'<div class="desk-card-front">'
      +'  <div class="desk-card-cont" style="background: url(<%=card.bgImg%>) no-repeat;">'
      +'    <ul>'
      +'      <li style="width: 100px;height: 60px;position: relative;z-index: 1000;margin-left: 60px;background: url(<%=card.icon%>) no-repeat;background-size:70px 60px"></li>'
      +'      <li><p><%=card.name%></p></li>'
      +'    </ul>'
      +'  </div>'
      +'  <div class="desk-card-title">'
      +'    <p><%=card.title%></p>'
      +'  </div>'
      +'</div>'
      +'<div class="desk-card-reverse">'
      +'  <div class="row">'
      +'    <div class="desk-card-reverse-1">'
      +'      <ul><img src="<%=card.icon%>" height="60px" width="60px"></ul>'
      +'      <ul> '
      +'        <li><p><%=card.name%></p></li>'
      +'        <li><p><%=card.title%></p></li>'
      +'      </ul>'
      +'    </div>'
      +'  </div>'
      +'  <div class="row">'
      +'    <div class="desk-card-reverse-2">'
      +'      <ul class="desk-card-reverse-2-remark"><p><%=card.remark%></p></ul>'
      +'    </div>'
      +'  </div>'
      +'</div>'
    +'</div>',
  },
  __init__:function(options){
    this.config= $.extend(false, this.defaultOptions, options);
    this.store = ai.getJsonStore(this.config.sql);
    this.groupStore = ai.getJsonStore(this.config.groupSql);
    this.create();
  },
  create:function(){
    if(this.store.getCount()==0) return;
    //获取分类信息
    for(var i = 0; i < this.groupStore.root.length; i++){
      $("#" + this.config.tabId).append(_.template(this.config.tabTpl)(this.groupStore.root[i]));
      $("#" + this.config.contentId).append(_.template(this.config.contentTpl)(this.groupStore.root[i]));
      if(i == 0){
        $("#" + this.config.tabId).children().last().addClass("active");
        $("#" + this.config.contentId).children().last().addClass("active").addClass("in");
      }
    }
    //将产品纳入分类tab中
    for(var i = 0; i < this.store.getCount(); i++){
      var record = this.store.getAt(i);
      var url = record.get('URL')||('/{contextPath}/ftl/frame/metaframe?modelcode='+record.get('SOFTSYSCODE'));
      url = url.indexOf('{contextPath}')!=-1?url.replace('{contextPath}',contextPath):"/"+contextPath+"/"+url;
      var card = {
        id:record.get('SOFTSYSCODE'),
        name:record.get('SYSTEM_NAME'),
        title:record.get('SYSTEM_NAME'),
        colClass:'col-md-'+(12/this.config.colSize),
        bgImg:'/' + contextUrl + '/dacp-res/catalog/dataportal/images/'+record.get('IMAGEINDEX'),
        icon:'/' + contextUrl + '/dacp-res/catalog/dataportal/images/'+record.get('IMAGES'),
        remark:record.get('REMARK'),
        url:url
      }
      var $divrow = $("#type-" + record.get("TYPECODE")).children().last();
      if($divrow.length == 0 || $divrow.length >= this.config.colSize){
        $("#type-" + record.get("TYPECODE")).append('<div class="row"></div>');
      }
      $("#type-" + record.get("TYPECODE")).children().last().append(
        _.template(this.config.cardTpl)({card:card}));
    }
    this.buildEvent();
  },
  buildEvent:function(){
    $(".desk-card").mouseover(function(){
      $(this).find('.desk-card-reverse').show();
    });
    $(".desk-card").mouseout(function(){
      $(this).find('.desk-card-reverse').hide();
    });
    $(".desk-card").click(function(){
      var _url=$(this).attr("ref");
      if(!_url) return false;
      if(_url.indexOf("opener=window")>=0){
        window.open(_url);
        return false;
      };
      var id=$(this).attr("id");
      var title=$(this).attr("name");
      ai.addTabSheet(id,title, _url,true)
    });
  },
  reload:function(sql){
    this.store.select(sql);
    this.create();
  }
});

/*根据传入的sqlcode，
查询出对应的数据，
返回结果封装到html中*/
AI.FillPage = Event.$extend({
  defaultOptions : {
    //containerId : 'keyInfoContainer',
    //store : [{var1 : "---", var2 : "---"}, {var1 : "---", var2 : "---"}],
    //maxSize:6,//最多显示多少条
    loopTpl:true,//是否循环使用模板填充数据
    //cardTpl:'',
    //onlyOnceFunc:,//只执行一次, 调用reload不重新执行
  }, 
  __init__:function(options){
    this.config= $.extend(false, this.defaultOptions, options);
    if(this.config.onlyOnceFunc) this.config.onlyOnceFlag = true;
    if($("#" +this.config.containerId).length != "0" && (this.config.store || this.config.jsonStore)){
      this.control = $("#" +this.config.containerId);
      this.create();
    }
  },
  create:function(){
    store = this.config.store || this.config.jsonStore.root;
    if(!store){
      this.buildEvent();
      return;
    }
    var appendHtml = "";
    if(this.config.loopTpl){
      for(var i in store){
        //for(var prop in store[i]) if(!store[i][prop]) store[i][prop] = "--";
        appendHtml += _.template(this.config.cardTpl)(store[i]);
      }
    }else{
      appendHtml = _.template(this.config.cardTpl)(store);
    }
    this.control.append(appendHtml);
    this.buildEvent();
  },
  buildEvent:function(){
    if(this.config.callback) this.config.callback();
    if(this.config.onlyOnceFlag){
      this.config.onlyOnceFunc();
      this.config.onlyOnceFlag = false;
    }
  },
  reload:function(sql){
    this.create();
  }
});

//传入单个或者数组形式的指标编码，获取对应指标值和名称
function getZB(zbcodes){
  var retData;
  $.ajax({
    async: false,
    url: '/' + contextUrl + "/catalog/zb/select?zbcodes=" + zbcodes, 
    type: "GET",
    dataType: "json",
    success: function(data){
                retData = data;
             }
  });
  return retData;
}

//对象转为数组
function objToArray(data){
  var returnArr=[];
  for(i in data){
    returnArr[returnArr.length] = data[i];
  }
  console.log(returnArr);
  return returnArr;
}

//数据库分类信息foamtree展示 
function buildTreeData(){
  var data =[];
  function getChildNodes(pNode){
    for(var i=0;i<ds_metamodel.getCount();i++){
      var r=ds_metamodel.getAt(i);
      if(r.get('PARENTCODE') != pNode.id) continue;
      var node={id:r.get('RULECODE'), label:r.get('RULENAME'), weight:r.get('NUM'), groups:[]};
      pNode.groups.push(node);
      getChildNodes(node);
      pNode.weight += node.weight;
    };
  };
  ds_metamodel = ai.getJsonStore(
    "SELECT a.rulecode,a.rulename,a.parentcode,a.dbname,COUNT(b.topiccode) num FROM "+ 
    "(SELECT * FROM metadb_struct WHERE UPPER(dbname)='STDCAT') a LEFT JOIN tablefile b "+ 
    "ON a.rulecode=b.topiccode GROUP BY a.rulecode,a.rulename,a.parentcode,a.dbname "
  );
  for(var j = 0; j < ds_metamodel.getCount(); j++){
    var r = ds_metamodel.getAt(j);
    if(r.get('PARENTCODE') != null && r.get('PARENTCODE') != "") continue;
    var node = {id:r.get('RULECODE'), label:r.get('RULENAME'), weight:r.get('NUM'), groups:[]};
    data.push(node);
    getChildNodes(node);
  }
  console.log("---foamtree---data")
  console.log(data);
  return data;
};

//点击卡片，加载页面
function clickCard(_href, _container){
  $("#" + _container).closest('.op-data-item').click(function(){
    var $a = $(window.parent.document).find("a[href='#" + _href + "']");
    if($a.length == 0){
      var store = ai.getJsonStore("SELECT modelname,url FROM metamodel WHERE modelcode='" + _href + "'");
      if(store.getCount() >=1 ){
        var r = store.getAt(0);
        ai.addTabSheet( _href, r.get("MODELNAME"), 
                       r.get("URL").replace("{contextPath}",contextPath), true)
      }
    }else{
      $a[0].click();
    }
  })
}

//查看系统消息
function showSysNotice(id){
  var noticeStore = ai.getJsonStore("SELECT * FROM sys_notice WHERE xmlid='" + id +"'").root;
  var noticeTpl = '<div id="sysNoticeModal" class="modal fade">' +
      '<div class="modal-dialog">' +
      '<div class="modal-content">' +
         '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal">  &times; </button>' +
            '<h4 class="modal-title"><%=NOTICE_TITLE%></h4>' +
            '<h7 class="modal-date"><%=new Date(CREATE_TIME).format("yyyy-mm-dd")%></h7>' +
         '</div>' +
         '<div class="modal-body"><p><%=NOTICE_CONTENT%></p></div>' +
         '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" data-dismiss="modal">关闭 </button>' +
         '</div>' +
      '</div>' +
      '</div>' +
    '</div>'; 
  $("#modalContainer").html(_.template(noticeTpl)(noticeStore[0]));
  $('#sysNoticeModal').modal('show');
}

$(document).ready(function(){
  
  /* 搜索框 */
  var serachWrap = new AI.Serach({
    containerId : "serach-container",
    clickFunc : function(){
        var keyword=$("#keyword").val();
        var objtype=$("#dropdown-default").attr("data-objtype");
        var url = "/" + contextPath + "/ftl/catalog/dataindex/viewIndex" +
                  "?keyword=" + keyword + "&objtype=" + objtype;
        ai.addTabSheet("DATACATALOG-04-02", "看数据", url, true);
    }
  });

  /* 关键信息 */
  var keyInfo = new AI.FillPage({
      containerId : 'keyInfoContainer',
      store : objToArray(getZB(["userNum","teamNum","tableNum","columnNum"])),
      cardTpl:'<div class="key-info-item fl">' + 
                '<span class="key-info-v"><%=value%></span>' + 
                '<span class="key-info-k"><%=name%></span>' + 
              '</div>',
      callback : function(){
        //系统管理员可以进入配置管理界面
        if("sys" == _UserInfo.username ){
          $(".setting-manage").append('<span class="i-set-manage"></span>');
          $(".setting-manage").append('<span class="setting-a">配置管理</span>');
          $(".setting-a").click(function(){
            ai.addTabSheet("setting-manage","配置管理", 
              "/" + contextUrl + "/ftl/dataindex/ai.data.indexfrm?tpl=HFlatTreeTabpanel&prodcode=DATA_PORTAL_00",
              true);
          })
        }
      }
  });

  /* 卡片 */
  new AI.FillPage({
      containerId : "seeDataContainer",
      store : getZB(["dbNum","dbCatNum","tableNum"]),
      loopTpl:false,
      cardTpl : '<div>共 <span class="op-data-num"><%=dbNum.value%></span> 个数据库</div>' +
                '<div>共 <span class="op-data-num"><%=dbCatNum.value%></span> 种分类</div>' +
                '<div>共 <span class="op-data-num"><%=tableNum.value%></span> 张表</div>',
      callback : function(){
        clickCard("DATACATALOG-04-02",this.containerId);
      }
  });
  new AI.FillPage({
      containerId : "dealDataContainer",
      store : getZB(["newTableNum","changeTableNum"]),
      loopTpl:false,
      cardTpl : '<div>共 <span class="op-data-num"><%=newTableNum.value%></span> 张新建表</div>' +
                '<div>共 <span class="op-data-num"><%=changeTableNum.value%></span> 张变更表</div>',
      callback : function(){
        clickCard("DATACATALOG-04-03",this.containerId);
      }
  });
  new AI.FillPage({
      containerId : "manageDataContainer",
      store : getZB(["dbNum","dbCatNum","tableNum"]),
      loopTpl:false,
      cardTpl : '<div>共 <span class="op-data-num"><%=dbNum.value%></span> 受控</div>' +
                '<div>共 <span class="op-data-num"><%=dbNum.value%></span> 未受控</div>',
      callback : function(){
        clickCard("DATAPORTAL_03",this.containerId);
      }
  });
  new AI.FillPage({
      containerId : "protectDataContainer",
      store : getZB(["dbNum","dbCatNum","tableNum"]),
      loopTpl:false,
      cardTpl : '<div>共 <span class="op-data-num"><%=dbNum.value%></span> 下线</div>' +
                '<div>共 <span class="op-data-num"><%=dbNum.value%></span> 异常程序</div>',
      callback : function(){
        clickCard("DATAPORTAL_02",this.containerId);
      }
  });

  /* 系统消息 */
  var sysNote = new AI.FillPage({
      containerId : "sysNoteContainer",
      jsonStore : new AI.JsonStore({
                sql : "SELECT XMLID, NOTICE_TITLE, CREATE_TIME FROM sys_notice ORDER BY create_time DESC",
                pageSize : 7,
              }),
      cardTpl : '<div class="note-item" data-xmlid="<%=XMLID%>">' + 
                  '<span class="note-content"><%=NOTICE_TITLE.length<25 ? NOTICE_TITLE : (NOTICE_TITLE.substr(0,25) + "...")%></span>' + 
                  '<span class="note-date"><%=new Date(CREATE_TIME).format("yyyy-mm-dd")%></span>' + 
                '</div>',
      callback : function(){
          $(".note-item").click(function(){
            showSysNotice($(this).data("xmlid"));
          });
      },
      onlyOnceFunc : function(){
          var totalCount = Math.floor(ai.getJsonStore("SELECT count(*) as num from sys_notice").getAt(0).get("NUM") / this.jsonStore.pageSize);
          $("#pre-sysN").click(function(){
              var curPage = $("#curPage").attr("data-page");
              if(curPage <= 0) return;
              $("#sysNoteContainer").empty();
              $("#curPage").attr("data-page", --curPage);
              sysNote.config.jsonStore.start = sysNote.config.jsonStore.pageSize * curPage;
              sysNote.config.jsonStore.pageSelect();
              sysNote.reload();
          })
          $("#next-sysN").click(function(){
              var curPage = $("#curPage").attr("data-page");
              if(curPage >= totalCount) return;
              $("#sysNoteContainer").empty();
              $("#curPage").attr("data-page", ++curPage);
              sysNote.config.jsonStore.start = sysNote.config.jsonStore.pageSize * curPage;
              sysNote.config.jsonStore.pageSelect();
              sysNote.reload();
          })
      }
  });

  /* 数据目录 */
  var dataCatalog = new AI.FillPage({
  	containerId : 'dataCataContainer',
  	jsonStore : ai.getJsonStore("SELECT a.catalog_code,a.catalog_name,a.catalog_type,a.icon_path,a.remark,COUNT(b.dbname) num " +
  			"FROM data_catalog_def a LEFT JOIN metadb_struct_obj b " +
  			"ON a.catalog_code=b.dbname GROUP BY a.catalog_code,a.catalog_name,a.catalog_type,a.icon_path,a.remark "),
  	cardTpl:'<li class="tile" data-code="<%=CATALOG_CODE%>" data-name="<%=CATALOG_NAME%>">' + 
  				'<a href="javascript:void(0);" class="deal_pic">' +
  					'<img src="<%=ICON_PATH ? ICON_PATH : "/"+contextUrl+"/dacp-res/catalog/dataindex/images/appminder1.png"%>" alt="专辑图标">' +
  				'</a>' +
  				'<a href="javascript:void(0);" class="shop_info">' +
  				'<p class="shop_name">' +
  					'<%=CATALOG_NAME%>' +
  				'</p>' +
  				'<p class="shop_brief">' +
  					'<%=REMARK%>' +
  				'</p>' +
  				'</a>' +
  				'<p class="deal_info">' +
  					'<span class="price"><%=NUM%>个实体</span>'+
  				'</p>' +
  			'</li>',
  	callback : function(){
          $("#" + this.containerId).append('<li class="tile add-data-cata" style="height:'+$(".m_list").height()+'px;">+</li>');
          //点击跳转到看数据页面
          $("#" + this.containerId + ">li").click(function(){
        	  if(!$(this).data("code")) return;
              var url = "/" + contextPath + "/ftl/catalog/dataindex/viewIndex" +
                        "?casetype=catalog&objtype=tab&catalogcode=" + $(this).data("code") + "&catalogname=" + $(this).data("name");
              ai.addTabSheet("DATACATALOG-04-02", "看数据", url, true);
          });
          $("#catalogMgr,#" + this.containerId + " .add-data-cata").click(function(){
        	  ai.addTabSheet("DATACATALOG-xx-xx", "业务目录", "/" + contextPath + "/ftl/catalog/dataindex/catalogMgr", true);
          });
  	}
  });

  /* 快速入口 */
  var desktop = new AI.Desktop();
  
  /* 标准目录信息 */
  setTimeout(
    function(){new CarrotSearchFoamTree({
      id: "userDbContainer",
      dataObject: {
        groups: buildTreeData() 
      },
      groupLabelMinFontSize: 10,
      groupLabelMaxFontSize: 20,
      onGroupDoubleClick: function (event) {
        var group = event.group;
        if(!group || group.groups.length>0) return;
        var _url = "/"+contextPath+"/ftl/catalog/dataindex/viewIndex"
        		 + "?topiccode=" + group.id + "&rulecode=" + group.id;
        ai.addTabSheet("DATACATALOG-04-02", "看数据", _url, true)
      },
      onGroupClick: function (event) {
        console.log('onGroupClick');
        console.log(event);
      },
    })},500) 

})
